/*
 * Copyright (c) 2024 Huawei Technologies Co.,Ltd.
 *
 * openGauss is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 * http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 * -------------------------------------------------------------------------
 *
 * htap_global.h
 * HTAP common definitions.
 *
 * IDENTIFICATION
 * src/gausskernel/storage/htap/htap_global.cpp
 *
 * -------------------------------------------------------------------------
 */

#include "htap_global.h"

namespace htap {
struct ErrorDescriptor {
    ErrorDescriptor() : m_strDesc(nullptr), m_MOTRc(MOT::RC_NA) {}
    const char *m_strDesc;
    MOT::RC m_MOTRc;
};

struct HTAPErrorDescriptor {
    HTAPErrorDescriptor() : m_rc(HTAP_RC_INVALID) {}
    RC m_rc;
};

static ErrorDescriptor errDesc[HTAP_RC_MAX_VALUE];
static HTAPErrorDescriptor htapErrDesc[MOT::RC_MAX_VALUE];

class ErrorDescriptorRegister {
public:
    ErrorDescriptorRegister(RC rc, const char *strDesc, MOT::RC motRc)
    {
        ErrorDescriptor &errorDesc = errDesc[rc];
        errorDesc.m_strDesc = strDesc;
        errorDesc.m_MOTRc = motRc;
        if (motRc != MOT::RC_NA) {
            htapErrDesc[motRc].m_rc = rc;
        }
    }
};

#define HTAP_DECLARE_ERROR(name, desc, mot_value) static ErrorDescriptorRegister name##Error(name, desc, mot_value);

HTAP_DECLARE_ERROR(HTAP_RC_OK, "OK", MOT::RC_OK)
HTAP_DECLARE_ERROR(HTAP_RC_ERROR, "Error", MOT::RC_ERROR)
HTAP_DECLARE_ERROR(HTAP_RC_OOM, "Out of memory", MOT::RC_MEMORY_ALLOCATION_ERROR)
HTAP_DECLARE_ERROR(HTAP_RC_INVALID_CFG, "Invalid configuration", MOT::RC_NA)
HTAP_DECLARE_ERROR(HTAP_RC_INVALID_ARG, "Invalid argument", MOT::RC_NA)
HTAP_DECLARE_ERROR(HTAP_RC_SYSTEM_FAILURE, "System call failed", MOT::RC_NA)
HTAP_DECLARE_ERROR(HTAP_RC_RESOURCE_LIMIT, "Reached resource limit", MOT::RC_NA)
HTAP_DECLARE_ERROR(HTAP_RC_INTERNAL_ERROR, "Internal error", MOT::RC_NA)
HTAP_DECLARE_ERROR(HTAP_RC_INVALID_STATE, "Invalid state", MOT::RC_NA)
HTAP_DECLARE_ERROR(HTAP_RC_EVENT_DISCARDED, "Event discarded", MOT::RC_NA)
HTAP_DECLARE_ERROR(HTAP_RC_TABLE_NOT_FOUND, "Table not found", MOT::RC_TABLE_NOT_FOUND)

extern RC ToHTAPRc(MOT::RC rc)
{
    if (rc < MOT::RC_MAX_VALUE) {
        return htapErrDesc[rc].m_rc;
    }
    return HTAP_RC_ERROR;
}

const char *RcToString(RC rc)
{
    if (rc < HTAP_RC_MAX_VALUE) {
        return errDesc[rc].m_strDesc;
    }
    return "Unknown error";
}

} // namespace htap